package com.szc.fs.util;

import cn.hutool.core.date.DateUtil;
import com.szc.fs.config.JQRConstants;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @title: TokenUtil
 * @Author Liuyang Tian
 * @Date: 2023/2/16 9:41
 * @Version 1.0
 */
public class TokenUtil {

    /**
     * 签名的算法：把 timestamp + "\n" + 密钥 当做签名字符串，使用 HmacSHA256 算法计算签名，再进行 Base64 编码。
     * @return
     */
    public static String getToken(Long timestamp,String secret) throws InvalidKeyException, NoSuchAlgorithmException {
        String signStr = DateUtil.currentSeconds()+"\n"+secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(signStr.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] signData = mac.doFinal(new byte[]{});
        return new String(Base64.encodeBase64(signData));
    }
}
